package com.lazypeople.util;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lazypeople.domain.DownloadSetting;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class ConfigUtils {
    private static final String CONFIG_DIR = "config";
    private static final String CONFIG_FILE = CONFIG_DIR + File.separator + "idiotdownload.settings";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    static {
        try {
            File file = new File(CONFIG_FILE);
            // 确保配置目录存在
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 新增：加载整个配置对象
    public static DownloadSetting loadDownloadSetting() {
        try {
            File file = new File(CONFIG_FILE);
            if (file.exists() && file.length() > 0) {
                return objectMapper.readValue(new FileInputStream(file), DownloadSetting.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 返回默认配置
        return createDefaultSetting();
    }

    // 新增：保存整个配置对象
    public static void saveDownloadSetting(DownloadSetting setting) {
        try {
            objectMapper.writeValue(new FileOutputStream(CONFIG_FILE), setting);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 新增：创建默认配置
    private static DownloadSetting createDefaultSetting() {
        DownloadSetting setting = new DownloadSetting();
        setting.setDefaultSavePath(System.getProperty("user.home"));
        setting.setThreadCount(4);
        setting.setMaxTaskCount(5);
        // 可添加其他配置项的默认值
        return setting;
    }
}